import React, { useEffect, useState, useCallback } from "react";
import { Switch, Redirect } from "react-router-dom";
import WrapRouter from "@/pages/common/WrapRouter";
import routes from "routes";

function Roots() {
  const [ renderRoutes, setRenderRoutes ] = useState(null);

  const renderRoute = useCallback(
    (routes) =>
      routes.map(({ children, ...route }) => {
        let routeView = null;
        if (children) {
          routeView = <Switch>{renderRoute(children)}</Switch>;
        }

        if (route.redirect) {
          return <Redirect key={route.redirect} to={route.redirect} />;
        } else {
          return (
            <WrapRouter {...route} routeView={routeView} key={route.path} />
          );
        }
      }),
    []
  );

  useEffect(() => {
    if (!renderRoutes) {
      setRenderRoutes(renderRoute(routes));
    }
  }, [ renderRoute, renderRoutes ]);

  return (
    <Switch>
      {renderRoutes}
    </Switch>
  );
}

export default Roots;
